package com.greenline.pay.web.common.cookie;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.greenline.framework.mursi.web.module.cookie.CookieModule;
import com.greenline.pay.web.common.constants.GlobalConstants;

/**
 * @Type UserCookieUtil
 * @Desc 用户信息的cookie操作工具类
 * @author weirui.shenwr
 * @date 2012-3-21
 * @Version V1.0
 */
public class UserCookieUtil extends CookieUtil {

    /**
     * 配置的用户id
     */
    public static final String USER_ID = "userId";

    /**
     * 配置的用户昵称
     */
    public static final String NICK_NAME = "nickName";
    public static final String USER_NAME = "userName";

    /**
     * 配置的登入ID
     */
    public static final String LOGIN_ID = "loginId";

    /**
     * 性别
     */
    public static final String SEX = "sex";

    /**
     * 手机号码，手机html5需要
     */
    public static final String MOBILE = "mobile";

    /**
     * 配置的用户登录类型
     */
    public static final String LOGINID_TYPE = "loginIdType";

    /**
     * cookie中设置的长session id
     */
    public static final String PER_SEEEIONID = "sessionId";

    /**
     * rms_user_id
     */
    public static final String RMS_USERID = "rmsUserId";

    /**
     * rms_user_id
     */
    public static final String CONTACT_NAME = "contactName";

    /**
     * rms_user_id
     */
    public static final String CONTACT_EMAIL = "contactEmail";

    /**
     * rms_user_id
     */
    public static final String CONTACT_MOBILE = "contactMobile";
    
    /**
     * 外部的登录用户id，cookie在rms域上，用于判断挂号网的用户是否已经切换
     */
    public static final String RMS_OUT_USERID ="rmsOutUserId";

    /**
     * 设置用户信息到cookie
     * 
     * @param request
     * @param user
     * @param expiry
     */
    public static void writeRmsInfo(HttpServletRequest request, CookieUser user) {

        if (request == null || user == null) {
            throw new IllegalArgumentException();
        }
        CookieModule jar = getCookieModule(request);
        if (jar == null) {
            throw new NullPointerException();
        }
        // 用户ID
        jar.set(RMS_USERID, user.getRmsUserId());
        jar.set(RMS_OUT_USERID, user.getRmsOutUserId());
        try {

            // 有中文必须encode如果为空必须移除原始数据
            if (StringUtils.isNotBlank(user.getContactName())) {
                jar.set(CONTACT_NAME, URLEncoder.encode(user.getContactName(), GlobalConstants.CHARACTER_ENCODING));
            } else {
                jar.remove(CONTACT_NAME);
            }

            if (StringUtils.isNotBlank(user.getContactEmail())) {
                jar.set(CONTACT_NAME, URLEncoder.encode(user.getContactEmail(), GlobalConstants.CHARACTER_ENCODING));
            } else {
                jar.remove(CONTACT_NAME);
            }

            if (StringUtils.isNotBlank(user.getContactMobile())) {
                jar.set(CONTACT_MOBILE, user.getContactMobile());
            } else {
                jar.remove(CONTACT_MOBILE);
            }

        } catch (UnsupportedEncodingException e) {
        }
    }

    /**
     * 通过cookie中是否有userId判断用户是否登入
     * 
     * @param request
     * @return boolean true是，false否
     */
    public static boolean isLogin(HttpServletRequest request) {
        Long userId = getUserId(request);
        if (userId != null) {
            return true;
        }
        return false;
    }

    /**
     * 清除cookie里的所有用户信息
     * 
     * @param request
     */
    public static void clearRmsInfo(HttpServletRequest request) {
        CookieModule jar = getCookieModule(request);
        if (jar != null) {
            jar.remove(RMS_USERID);
            jar.remove(RMS_OUT_USERID);
            jar.remove(CONTACT_NAME);
            jar.remove(CONTACT_MOBILE);
            jar.remove(CONTACT_EMAIL);
        }
    }

    /**
     * 获取用户的user_id
     * 
     * @param request
     * @return Long
     */
    public static Long getUserId(HttpServletRequest request) {
        String idStr = getCookieValue(request, USER_ID);
        if (StringUtils.isNumeric(idStr)) {
            return Long.valueOf(idStr);
        }
        return null;
    }

    /**
     * 获取用户的user_id
     * 
     * @param request
     * @return Long
     */
    public static Long getRmsUserId(HttpServletRequest request) {
        return getLongValue(request,RMS_USERID);
    }
    
    private static Long getLongValue(HttpServletRequest request,String name) {
        String idStr = getCookieValue(request, name);
        if (StringUtils.isNumeric(idStr)) {
            return Long.valueOf(idStr);
        }
        return null;
    }
    /**
     * 获取用户的user_id
     * 
     * @param request
     * @return Long
     */
    public static Integer getLoginIdType(HttpServletRequest request) {
        String idStr = getCookieValue(request, LOGINID_TYPE);
        if (StringUtils.isNumeric(idStr)) {
            return Integer.valueOf(idStr);
        }
        return null;
    }
    /**
     * 获取用户登录id
     * 
     * @param request
     * @return String
     */
    private static String getEncodeValue(HttpServletRequest request, String name) {
        String value = getCookieValue(request, name);
        try {
            if (value != null) {
                return URLDecoder.decode(value, GlobalConstants.CHARACTER_ENCODING);
            } else {
                return value;
            }
        } catch (UnsupportedEncodingException e) {
        }
        return "";
    }

    /**
     * 取得cookie里的usercookie对象
     * 
     * @param request
     * @return CookieUser
     */
    public static CookieUser getUserCookie(HttpServletRequest request) {
        CookieUser cuser = new CookieUser();
        cuser.setUserId(getUserId(request));
        cuser.setLoginId(getEncodeValue(request, LOGIN_ID));
        cuser.setNickName(getEncodeValue(request, NICK_NAME));
        cuser.setUserName(getEncodeValue(request, USER_NAME));
        cuser.setSex(getCookieValue(request, SEX));
        cuser.setLoginIdType(getLoginIdType(request));
        cuser.setRmsUserId(getRmsUserId(request));
        cuser.setRmsOutUserId(getCookieValue(request,RMS_OUT_USERID));
        cuser.setContactName(getEncodeValue(request, CONTACT_NAME));
        cuser.setContactMobile(getCookieValue(request, CONTACT_MOBILE));
        cuser.setContactEmail(getEncodeValue(request, CONTACT_EMAIL));

        return cuser;
    }

    /**
     * 获取长sessionId
     * 
     * @param request
     * @return String
     */
    public static String getSessionId(HttpServletRequest request) {
        return getCookieValue(request, PER_SEEEIONID);
    }

}
